#!/bin/bash 

CONTROL_FILE=DEBIAN/control
LIST_UKUICHROOT=~/packages_with_amd64_suffix.txt
# 获取脚本的绝对路径，考虑符号链接  
ABS_PATH=$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0")  
# 提取脚本所在的目录  
SCRIPT_DIR=$(dirname "$ABS_PATH")
FINISH_ARGS_FILE="$4"


check_depends()
{

 # 使用grep提取Depends信息  
local dependencies=$(grep "^Depends:" "$CONTROL_FILE" | sed 's/Depends://')
local dependsneeddl_array=()

 # 使用逗号分隔提取的字符串，并遍历输出
 IFS=',' read -r -a depends_array <<< "$dependencies"
 for item in "${depends_array[@]}"; do
     cleaned_string="${item%% \(*>*}"  #清除包名后面的版本号
     if [[ "$cleaned_string" == "$item" ]]; then
	 cleaned_string="${item%% \(*=*}" 
     fi
     echo "清除版本号后包名为 '$cleaned_string'" 
     grep -q $cleaned_string: $LIST_UKUICHROOT
     if [ ! $? -eq 0 ]; then
        echo "The string '$cleaned_string' was not found."
        dependsneeddl_array+=("$cleaned_string")
	for needdl in "${dependsneeddl_array[@]}"; do 
	    echo "depends数组中的内容 '$needdl'"
	done
     fi
 done

 if [ ${#dependsneeddl_array[@]} -eq 0 ]; then   #if dependsneeddl_array不为空
    echo "do not need download depend"
    return
 else
    for depend in "${dependsneeddl_array[@]}"; do
      mkdir $depend
      cd $depend
      apt download $depend
      echo "解压依赖'$depend'"
      dpkg-deb -R *.deb .
      cp -r ./usr/lib/x86_64-linux-gnu/* $SCRIPT_DIR/BUILD/lib
      check_depends
      cd ..
    done
 fi

}


download_depends()
{
 if [ ${#dependsneeddl_array[@]} -eq 0 ]; then   #if dependsneeddl_array不为空
    echo "do not need download depend"
    return
 else
    for depend in "${dependsneeddl_array[@]}"; do
      mkdir $depend
      cd $depend
      apt download $depend
      echo "解压依赖'$depend'"
      dpkg-deb -R *.deb .
      check_depends
      cd ..
     done
 fi
}

is_lib_empty() {
    local lib_dir="$1"
    if [[ -z "$(ls -A "$lib_dir")" ]]; then
      echo 1   # 返回1表示目录为空
    else
      echo 0   # 返回0表示目录不为空   
    fi
}

is_dir_exist() {
    local dir_path="$1"
    if [ -d "$dir_path" ]; then
      echo 1   # 返回1表示目录存在
    else
      echo 0   # 返回0表示目录不存在
    fi
}



filling_yml()
{
    local idname=$1    
    local command=$2
    local finish_args=$(<"$3")
    local lib_is_empty=$(is_lib_empty "./lib")
    local etc_dir_is_exist=$(is_dir_exist "./etc")
    local schemas_dir="./app/usr/share/glib-2.0/schemas"
    local post_install="post-install:
      - glib-compile-schemas /app/share/glib-2.0/schemas
    "    
    local bin_path=$(find . -type f -name $2 -executable)
    local pure_bin_path=$(dirname "$bin_path")
    local build_option="build_options:
      env:
        PATH: $pure_bin_path:/app/bin:/usr/bin
    "

    echo "lib is empty '${lib_is_empty}'"  

    mv ./usr ./app/
    if [ "$etc_dir_is_exist" -eq 0 ]; then
    local build_command=" 
      - cp -r ./usr/* /app/"
    else
    mv ./etc ./app/
    local build_command=" 
      - cp -r ./usr/* /app/
      - cp -r ./etc /app/"
    fi

    #沙箱内默认动态库地址为/app/lib,其他地址无法链接到
    if [ -d "./app/usr/lib/x86_64-linux-gnu" ]; then
        echo "cp lib"
        cp -r ./app/usr/lib/x86_64-linux-gnu/* ./app/usr/lib/
    fi


# 定义YAML文件内容
yaml_content="id: $idname
runtime: top.openkylin.Platform
runtime-version: "2.0"
sdk: top.openkylin.Sdk
command: $command
finish-args:
$finish_args
modules:
"
    # 根据lib文件夹是否为空，动态添加deps-libs模块
    if [ "$lib_is_empty" -eq 0 ]; then
        yaml_content+="  - name: deps-libs
    buildsystem: simple
    build-commands:
      - mkdir /app/lib  
      - cp -r * /app/lib/
    sources:
      - type: dir
        path: ./lib
"
    fi 

    yaml_content+="  - name: $command
    buildsystem: simple
    "
    if [ -d "$schemas_dir" ]; then
    yaml_content+="$post_install"
    fi

    #if [[ ! -z $4 ]]; then
    #yaml_content+="$build_option"
    #fi

    if [ ! "$pure_bin_path" = "./usr/bin" ]; then
    yaml_content+="$build_option"
    fi 

    yaml_content+="build-commands:$build_command
    sources:
      - type: dir
        path: ./app
"

	# 写入YAML文件
	output_file="$idname.yml"

	# 创建并写入文件
	echo "$yaml_content" > "$output_file"

	# 检查是否成功写入
	if [ $? -eq 0 ]; then
	  echo "YAML file '$output_file' created successfully."
	else
	  echo "Error creating YAML file."
	fi

}


update_filedesktop() {
  pwd
  local bin_name=$2 
  local flatpak_id=$1
  local desktop_file_path="./app/usr/share/applications/$bin_name.desktop"
  echo "------update_filedesktop-'$bin_name'-'$2'--"

  #找到./app/usr/share/applications/app.desktop文件
  if [ -f "$desktop_file_path" ]; then
      # 使用sed命令替换Icon字段的内容  
      sed -i 's/^Icon=.*$/Icon='$flatpak_id'/' "$desktop_file_path"  
    
      # 重命名文件  
      mv "$desktop_file_path" "./app/usr/share/applications/$flatpak_id.desktop"  
      echo "文件已更新并重命名成功。"  
  else  
      echo "文件 $desktop_file_path 不存在。"
  fi
}


# 检查是否提供了参数  
#if [ "$#" -ne 5 ]; then  
#    echo "需要四个参数,第一个为.deb文件名 第二个为包id及yml文件名 第三个command"
#    exit 1  
#fi  
  
# 检查文件是否存在  
if [ ! -f "$1" ]; then  
    echo "文件 $1 不存在"  
    exit 1  
fi  
  
# 检查文件扩展名是否为.deb  
if [[ "$1" != *.deb ]]; then  
    echo "提供的文件不是一个.deb包"  
    exit 1  
fi 

# 如果编译临时目录已存在，先清除
if [ -d BUILD ]; then
    echo "BUILD路径已存在，移除"
    rm -r BUILD
fi

mkdir BUILD
mkdir BUILD/lib
mkdir BUILD/app
# 使用dpkg-deb列出.deb包的内容  
dpkg-deb -R "$1" BUILD
cd BUILD

echo "脚本所在路径：$SCRIPT_DIR"
#----------------------分析contrl文件中的depend信息-------------------

check_depends

#---------------------------填充yml文件-------------------------------

echo "第二个参数为'$2' 第三个参数为'$3'"
echo "第四个参数为'$FINISH_ARGS_FILE' 第五个是'$5'"
filling_yml "$2" "$3" "../$FINISH_ARGS_FILE" "$5"

#-----------------------汉化及添加appdate文件--------------------------

update_filedesktop $2 $3

#--------------------------- 开始编译---------------------------------
flatpak-builder  --force-clean --verbose --repo=repo  $2.yml


